/*
 * @Description:
 * @Author:
 * @Date: 2024-10-21 21:50:58
 * @LastEditTime: 2024-10-23 07:22:11
 * @LastEditors: XXX
 */
import Koa, { Context } from 'koa'
import koaBody from 'koa-body'
import koaRouter from 'koa-router'
import logger from "koa-logger"
import cors from "koa2-cors"
import log4js from "log4js"
import chalk from "chalk";
import { ResultHander } from './middleware/resultHandler'
import { addRouter } from './router'

const app = new Koa()
app.use(cors())
const router = new koaRouter()

const port = 3300
const log4 = log4js.getLogger()
log4.level = "debug"

// 日志打印
app.use(logger(info => {
  log4.debug(info)
}))

app.use(koaBody())

app.use(async (ctx, next) => {
  await next()
  log4.debug(chalk.green('请求body: ') + JSON.stringify(ctx.request.body))
  log4.debug(chalk.green('返回数据: ') + JSON.stringify(ctx.body))
})

app.use(ResultHander())

// 加载路由
addRouter(router)

//启动路由
app.use(router.routes()).use(router.allowedMethods());

app.use(async (ctx: Context) => {
  console.log(123456)
  log4.error(`404 ${ctx.message}: ${ctx.href}`)
  ctx.status = 404
  ctx.body = "404! api not found!"
})

app.on('error', (err, ctx: Context) => {
  log4.error(err)
  ctx.status = 500
  if (ctx.app.env !== 'development') {
    ctx.res.end(err.stack)
  }
})

app.listen(port, () => {
  log4.debug("mock server running at http://localhost:%d", port)
})
